package com.rhcloud.insongr.srv.wechat.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rhcloud.insongr.srv.wechat.bean.AccessTokenBean;
import com.rhcloud.insongr.srv.wechat.constant.AppConstant;
import com.rhcloud.insongr.srv.wechat.util.WeixinUtil;


  
  
/**
 * 定时获取微信access_token的线程 
 * @author node1
 */
public class TokenThread implements Runnable {  
    private static Log log = LogFactory.getLog(TokenThread.class);   
  
    public void run() {  
        while (true) {  
            try {  
                AccessTokenBean accessTokenBean = WeixinUtil.getAccessTokenBean(AppConstant.APPID, AppConstant.APPSECRET);  
                if (accessTokenBean!=null) {
                    log.info("获取access_token成功，有效时长"+accessTokenBean.getExpires_in()+"秒,access_token="
                    		+accessTokenBean.getAccess_token());
                    // 休眠7000秒  
                    Thread.sleep((accessTokenBean.getExpires_in() - 200) * 1000);  
                } else {
                    // 如果access_token为null，60秒后再获取  
                    Thread.sleep(60 * 1000);  
                }  
            } catch (InterruptedException e) {  
                try {  
                    Thread.sleep(60 * 1000);  
                } catch (InterruptedException e1) {  
                    log.error("{}", e1);  
                }  
                log.error("{}", e);
            }  
        }  
    }  
    
    public static void main(String[] args) throws InterruptedException {
    	//IpBd6Ix22oaMR5SEXj7tYys1GIubgPcSW3m3Bkw61IfdSaaCTH-JRIKti86r2gTYOWZJd_Cp2RCSYuAsFMS5NGd3oGm4vkcxjhjNwNMoeuE
    	//7200秒
    	AccessTokenBean accessTokenBean = WeixinUtil.getAccessTokenBean(AppConstant.APPID, AppConstant.APPSECRET);  
        if (accessTokenBean!=null) {
            log.info("获取access_token成功，有效时长"+accessTokenBean.getExpires_in()+"秒,access_token="
            		+accessTokenBean.getAccess_token());
            // 休眠7000秒  
            Thread.sleep((accessTokenBean.getExpires_in() - 200) * 1000);  
        } else {
            // 如果access_token为null，60秒后再获取  
            Thread.sleep(60 * 1000);  
        }  
	}
}  
